package com.mac.sys.generator;


import java.sql.*;
import java.util.List;

/***
 *@Author:liangjilong
 *@Date:2015年12月5日下午12:25:12
 *@Email:jilongliang@sina.com
 *@Version:1.0
 *@CopyRight(c)Flong Intergrity Ltd.
 */
public class DBHelperUtils {
    private static final Connection conn;
    private static final String driverClass = PropertiesHelper.getValueByKey("jdbc.driver");
    private static final String connectionUrl = PropertiesHelper.getValueByKey("jdbc.url");
    private static final String username = PropertiesHelper.getValueByKey("jdbc.username");
    private static final String password = PropertiesHelper.getValueByKey("jdbc.password");

    private static DBHelperUtils instance = null;
    /**
     * 定义代码块.
     */
    static {
        try {
            Class.forName(driverClass);
//            conn = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/macsite?useUnicode=true&characterEncoding=utf-8", username, password);
            conn = DriverManager.getConnection(connectionUrl, username, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**建立单例模式
     * Single
     * @return
     */
    public static DBHelperUtils getInstance() {
        if (instance == null) {
            synchronized (DBHelperUtils.class) {
                instance = new DBHelperUtils();
            }
        }
        return instance;
    }


    /**
     * 查询数据
     * @param sql
     * @param params
     * @return
     */
    public static ResultSet query(String sql, List<Object> params) {
        System.out.println("sql: " + sql);
        //System.out.println("params: " + params);
        try {
            PreparedStatement psmt = conn.prepareStatement(sql);
            if(params != null) {
                for (int i = 0; i < params.size(); i++) {
                    psmt.setObject(i+1, params.get(i));
                }
            }
            return psmt.executeQuery();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /***
     * 更新
     * @param sql
     * @param params
     */
    public static void update(String sql, List<Object> params) {
        System.out.println("sql: " + sql);
        //System.out.println("params: " + params);
        try {
            PreparedStatement psmt = conn.prepareStatement(sql);
            if(params != null) {
                for (int i = 0; i < params.size(); i++) {
                    psmt.setObject(i+1, params.get(i));
                }
            }
            psmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取链接
     * @return
     */
    public static Connection getConnection(){
        try {
            Class.forName(driverClass);
            return DriverManager.getConnection(connectionUrl, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}
